var ffmpeg = require('fluent-ffmpeg');
const AWS = require('aws-sdk')
const s3 = new AWS.S3()
const { createReadStream } = require('fs')
const ffprobePath = '/opt/nodejs/ffprobe'
const ffmpegPath = '/opt/nodejs/ffmpeg'
const allowedTypes = ['mov', 'mpg', 'mpeg', 'mp4', 'wmv', 'avi', 'webm']


module.exports.handler = async (event, context) => {
  const srcKey = decodeURIComponent(event.Records[0].s3.object.key).replace(/\+/g, ' ')
  const bucket = event.Records[0].s3.bucket.name
  const destBucket = "mobile."+bucket
  const target = s3.getSignedUrl('getObject', { Bucket: bucket, Key: srcKey, Expires: 1000 })
  const fileName = srcKey.slice(srcKey.lastIndexOf("/")+1).replace(/\.\w+$/,'')
  let fileType = srcKey.match(/\.\w+$/)

  if (!fileType) {
    throw new Error(`invalid file type found for key: ${srcKey}`)
  }

  fileType = fileType[0].slice(1)

  if (allowedTypes.indexOf(fileType) === -1) {
    throw new Error(`filetype: ${fileType} is not an allowed type`)
  }

  function createImage() {
    ffmpeg.setFfmpegPath(ffmpegPath)
    ffmpeg.setFfprobePath(ffprobePath)
    return new Promise((resolve, reject) => {
        ffmpeg(target).screenshots({
            count: 1,
            filename: fileName+'.png',
            timestamps:['.1%'],
            size:"320x240",
            folder:"/tmp/"
        }).on("end",function(){
            resolve()
        }).on("error",function(error){
            console.log(error)
            reject()
        })
    })
  }

  function uploadToS3() {
    return new Promise((resolve, reject) => {
      let tmpFile = createReadStream(`/tmp/${fileName}.png`)
      const dstKey = srcKey.replace(/\.\w+$/, '.png')
      var params = {
        Bucket: destBucket,
        Key: dstKey,
        Body: tmpFile,
        ContentType: `image/png`
      }

      s3.upload(params, function(err, data) {
        if (err) {
          console.log(err)
          reject()
        }
        console.log(`successful upload to ${destBucket}/${dstKey}`)
        resolve()
      })
    })
  }
  await createImage();
  await uploadToS3();
}
